import struct
import decode
from optparse import OptionParser

def extractFirmware( data ):
  s = ''.join( data )

  # Make sure to use big-endian '>' when unpacking
  (count, headerLen) = struct.unpack_from( '>II', s, offset=0x20 )

  pos = 0x30

  firmwares = {}

  for i in range(count):
    filename = s[pos:pos+0x10]
    # Eh... don't know a better way at the moment to remove the null characters
    # If we don't do this, open() complains at us
    for i in range(len(filename)):
      if ord(filename[ i ]) == 0:
        print i
        filename = filename[0:i]
        break
    pos += 0x10

    (start, length) = struct.unpack_from( '>II', s, offset=pos )
    pos += 0x10
    firmwares[ filename ] = s[ start:start+length ]
  return firmwares


def extractFirmwareFromFile( filename ):
  f = open( filename, 'rb' )
  data = f.read()
  f.close()

  return extractFirmware( data )

if __name__ == '__main__':
  parser = OptionParser()

  (options, args) = parser.parse_args()

  if len( args ) < 1:
    raise Exception( 'No Input File Provided' )

  data = decode.decodePackageFile( args[0] )

  firmwares = extractFirmware( data )
  for i, j in firmwares.iteritems():
    print i.encode()
    f = open( i.encode('utf-8'), 'wb' )
    f.write( j )
    f.close()




